import express from "express";
import { PrismaClient } from "@prisma/client";
import { CreateId, Check, Result, Time } from "@/utils";

const prisma = new PrismaClient();
const router = express.Router();

router.post("/create", async (req, res) => {
   const { name }: Role.Create = req.body;
   if (!Check.Required([name])) return res.send(Result.Error("参数错误"));

   // 角色名称不可重复
   const value = await prisma.mp_role.findMany({ where: { name } });
   if (value.length > 0) return res.send(Result.Error("角色名称不可重复"));

   const id = await CreateId.One("mp_role");
   const { userId } = req;

   await prisma.mp_role.create({
      data: {
         id,
         name,
         permission: "",
         status: "OPEN",
         created_by: userId,
         created_time: Time.Now()
      }
   });

   res.send(Result.OK());
});

router.post("/delete", async (req, res) => {
   const { id }: Role.Delete = req.body;
   if (!Check.Required([id])) return res.send(Result.Error("参数错误"));
   const role = await prisma.mp_role.findUnique({ where: { id } });

   if (!role) return res.send(Result.Error("角色不存在"));
   if (role.super_admin) return res.send(Result.Error("超级管理员角色不可删除"));

   await prisma.mp_role.delete({ where: { id } });

   res.send(Result.OK());
});

router.post("/update", async (req, res) => {
   const { id, name, status, super_admin }: Role.Update = req.body;
   if (!Check.Required([id])) return res.send(Result.Error("参数错误"));

   // 超级管理员角色唯一
   if (!!super_admin) {
      const role = await prisma.mp_role.findMany({ where: { super_admin } });
      if (role.length > 0) {
         if (role[0].id != id) return res.send(Result.Error("只能拥有一个超级管理员角色"));
      }
   }

   const oldValue = await prisma.mp_role.findUnique({ where: { id } });
   if (!oldValue) return res.send(Result.Error("当前条目不存在"));

   await prisma.mp_role.update({
      where: { id },
      data: {
         name: name ? name : oldValue.name,
         status: status ? status : oldValue.status,
         super_admin: Boolean(super_admin)
      }
   });

   res.send(Result.OK());
});

router.get("/search", async (req, res) => {
   const list = await prisma.mp_role.findMany({
      select: {
         id: true,
         name: true,
         status: true,
         super_admin: true
      }
   });

   return res.send(Result.OK(list));
});

export const role = router;
